package com.cndongtai.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.cndongtai.po.User;

public class CookieUtils {
	public static final String USER_COOKIE = "user.cookie";  
	static Logger log = Logger.getLogger(CookieUtils.class);
	    // 添加一个cookie   
	    public static Cookie addCookie(User user) {  
	    	String name="";
			try {
				name = URLEncoder.encode(user.getUsername(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				log.error(e.getMessage());
			}
			
	        Cookie cookie = new Cookie(USER_COOKIE, name+","
	        		+user.getPassword());
	        cookie.setMaxAge(60 * 60 * 24 * 365);// cookie保存一年  
	        cookie.setPath("/");
	        return cookie;  
	    }  
	  
	    // 得到cookie   
	    public static String[] getCookie(HttpServletRequest request) {  
	        Cookie[] cookies = request.getCookies();  
	        if (cookies != null) {  
	            for (Cookie cookie : cookies) {  
	            	String name = cookie.getName();
	                if (CookieUtils.USER_COOKIE.equals(name)) {  
	                    String value = cookie.getValue();  
	                    if (value != null && !"".equals(value)) {  
	                        String[] split = value.split(",");  
	                        String username = split[0];  
	                        try {
	                        	username = java.net.URLDecoder.decode(username, "UTF-8");
	            			} catch (UnsupportedEncodingException e) {
	            				// TODO Auto-generated catch block
	            				log.error(e.getMessage());
	            			}
	                        String password = split[1];
	                        String [] cookiedArr={username, password};
	                            return cookiedArr;  
	                    }  
	                }  
	            }  
	        }  
	        return null;  
	    }  
	  
	    // 删除cookie   
	    public static Cookie delCookie(HttpServletRequest request) {  
	        Cookie[] cookies = request.getCookies();  
	        if (cookies != null) {  
	            for (Cookie cookie : cookies) {  
	                if (USER_COOKIE.equals(cookie.getName())) {  
	                    cookie.setValue("");  
	                    cookie.setMaxAge(0);  
	                    cookie.setPath("/");
	                    return cookie;  
	                }  
	            }  
	        }  
	        return null;  
	    }  
}
